import { defineStore } from 'pinia'
import api from '@/api'

export const useServerStore = defineStore('server', {
  state: () => ({
    servers: [],
    loading: false,
    error: null
  }),

  getters: {
    activeServers: (state) => state.servers.filter(server => server.status === 'active'),
    totalServers: (state) => state.servers.length
  },

  actions: {
    async fetchServers() {
      this.loading = true
      try {
        const response = await api.get('/servers/list')
        this.servers = response.data
        this.error = null
      } catch (error) {
        this.error = error.message
        console.error('获取服务器列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    async createServer(serverData) {
      try {
        const response = await api.post('/servers/', serverData)
        this.servers.push(response.data)
        return response.data
      } catch (error) {
        console.error('创建服务器失败:', error)
        throw error
      }
    },

    async updateServer(id, serverData) {
      try {
        const response = await api.put(`/servers/${id}`, serverData)
        const index = this.servers.findIndex(s => s.id === id)
        if (index !== -1) {
          this.servers[index] = response.data
        }
        return response.data
      } catch (error) {
        console.error('更新服务器失败:', error)
        throw error
      }
    },

    async deleteServer(id) {
      try {
        await api.delete(`/servers/${id}`)
        this.servers = this.servers.filter(s => s.id !== id)
      } catch (error) {
        console.error('删除服务器失败:', error)
        throw error
      }
    }
  }
})